from django.shortcuts import render

# Create your views here.

from rest_framework.viewsets import GenericViewSet, ViewSet, ModelViewSet
from .models import Order
from .serializer import OrderSerializer, PaySuccessSerializer
from django_filters.rest_framework import DjangoFilterBackend
from utils.view import CommonListModelMixin
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework.permissions import IsAuthenticated
from utils.response import APIResponse
from rest_framework.exceptions import APIException
from rest_framework.response import Response
from utils.loggings import logger
from rest_framework.mixins import CreateModelMixin
from django.db import transaction
from car.models import ShopCar
from goods.models import GoodsShelf


class OrderView(ModelViewSet, CommonListModelMixin):
    queryset = Order.objects.all().filter(is_delete=False, is_show=True)
    serializer_class = OrderSerializer
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ['user_id', 'order_status', 'id']


class AliPayView(GenericViewSet, CreateModelMixin):
    queryset = Order
    serializer_class = PaySuccessSerializer
    authentication_classes = [JSONWebTokenAuthentication]
    permission_classes = [IsAuthenticated]

    def _stock_num(self, i):
        goods_id = i.get('goods_info').get('id')
        stock_num = GoodsShelf.objects.filter(id=goods_id).values()[0].get('stock_num')
        if stock_num < 1:
            return stock_num
        return 'ok'

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data, context={'request': request})
        serializer.is_valid(raise_exception=True)
        if serializer.initial_data.get('commodity_list')[0].get('user_id'):
            with transaction.atomic():
                for i in serializer.initial_data.get('commodity_list'):
                    stock_num = self._stock_num(i)
                    if not stock_num == 'ok':
                        goods_name = i.get('goods_info').get('name')
                        return APIResponse(code=101, msg=f'商品"{goods_name}"库存中只剩:{stock_num}')
                    ShopCar.objects.filter(id=i.get('id')).delete()
                    continue
                serializer.save()
                pay_url = serializer.context.get('pay_url')
                return APIResponse(pay_url=pay_url)
        else:
            for i in serializer.initial_data.get('commodity_list'):
                stock_num = self._stock_num(i)
                if not stock_num == 'ok':
                    goods_name = i.get('goods_info').get('name')
                    return APIResponse(code=101, msg=f'商品"{goods_name}"库存中只剩:{stock_num}')
                continue
            serializer.save()
            pay_url = serializer.context.get('pay_url')
            return APIResponse(pay_url=pay_url)


class PaySuccessView(ViewSet):
    def list(self, request):
        try:
            order_form = request.query_params.get('out_trade_no')
            Order.objects.get(order_form=order_form, pay_status=1)
            return APIResponse()
        except Exception as e:
            raise APIException('订单还未支付成功')

    def create(self, request):
        try:
            result_data = request.data.dict()
            out_trade_no = result_data.get('out_trade_no')
            signature = result_data.pop('sign')
            from libs import alipay_common
            result = alipay_common.alipay.verify(result_data, signature)
            if result and result_data["trade_status"] in ("TRADE_SUCCESS", "TRADE_FINISHED"):
                Order.objects.filter(order_form=out_trade_no).update(pay_status=1,
                                                                     order_status=1,
                                                                     pay_time=result_data.get('gmt_payment'),
                                                                     trade_no=result_data.get('trade_no'))
                order_obj = Order.objects.filter(order_form=out_trade_no).first()
                res = order_obj.order_goods.all()
                for item in res:
                    goods_obj = GoodsShelf.objects.filter(id=item.goods_id).first()
                    sales_num = goods_obj.sales_num + int(item.buy_num)
                    stock_num = goods_obj.stock_num - int(item.buy_num)
                    GoodsShelf.objects.filter(id=item.goods_id).update(sales_num=sales_num, stock_num=stock_num)
                logger.warning(f'{out_trade_no}订单支付成功')
                return Response('success')
            else:

                logger.error(f'{out_trade_no}订单支付失败')
                return Response('failed')
        except:
            return Response('failed')
